package com.franklin.validation.tool;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Description :
 * Create By: Franklin
 * Date : 2020/6/18 16:44
 */
public class HelloWorldAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        //获取当前在操作的工程上下文
        Project project = e.getData(PlatformDataKeys.PROJECT);

        //获取当前操作的类文件
        PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
        //获取当前类文件的路径
        String classPath = psiFile.getVirtualFile().getPath();
        String title = "Hello World!";

        //获取当前时间触发时，光标所在的元素
        PsiElement psiElement = e.getData(LangDataKeys.PSI_ELEMENT);
        //如果光标选择的不是类，弹出对话框提醒
        if (psiElement == null || !(psiElement instanceof PsiClass)){
            //显示对话框
            Messages.showMessageDialog(project,"please focus on a class","Generate Failed",Messages.getInformationIcon());
        }

        List<PsiClass> classes = this.getClasses(psiElement);
        classes.forEach(clazz -> {
            String qualifiedName = clazz.getQualifiedName();
            System.out.println(qualifiedName);
            PsiAnnotation[] annotations = clazz.getModifierList().getAnnotations();
            Arrays.stream(annotations)
                    .forEach(psiAnnotation -> {
                        PsiNameValuePair[] attributes = psiAnnotation.getParameterList().getAttributes();
                        for (PsiNameValuePair attribute : attributes) {
                            System.out.println(attribute.getName());
                        }
                    });
            PsiMethod[] allMethods = clazz.getAllMethods();
            Arrays.stream(allMethods)
                    .forEach(method -> {
                        System.out.println(method.getName());
                        System.out.println(method.getHierarchicalMethodSignature());
                    });
        });
    }

    private List<PsiClass> getClasses(PsiElement element){
        List<PsiClass> elements = new ArrayList<>();
        PsiClass psiClass = (PsiClass) element;
        elements.add(psiClass);
        List<PsiClass> classElements = PsiTreeUtil.getChildrenOfTypeAsList(element, PsiClass.class);
        elements.addAll(classElements);
        classElements
                .stream()
                .map(this::getClasses)
                .forEach(elements::addAll);
        return elements;
    }
}
